package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import com.ruoyi.common.domain.AOss;
import com.ruoyi.common.mapper.AOssMapper;
import com.ruoyi.common.utils.Assert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WeChatUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MultipartFileImpl;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.ATeamVO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.util.LoginUtils;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IATeamService;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.Oneway;

/**
 * 团队Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-16
 */
@Service
@Transactional
public class ATeamServiceImpl implements IATeamService {
    @Autowired
    private ATeamMapper aTeamMapper;

    @Autowired
    private ATeamInfoMapper aTeamInfoMapper;

    @Autowired
    private AUserMapper aUserMapper;

    @Autowired
    private ConfigureGlobalMapper configureGlobalMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private AOssMapper aossMapper;

    /**
     * 查询团队
     *
     * @param id 团队主键
     * @return 团队
     */
    @Override
    public ATeamVO selectATeamById(Long id) {
        return aTeamMapper.selectATeamById(id);
    }

    /**
     * 查询团队列表
     *
     * @param ATeamvo 团队
     * @return 团队
     */
    @Override
    public List<ATeamVO> selectATeamList(ATeamVO ATeamvo) {
        return aTeamMapper.selectATeamList(ATeamvo);
    }

    /**
     * 新增团队
     *
     * @param aTeam 团队
     * @return 结果
     */
    @Override
    public int insertATeam(ATeam aTeam) {
        if (StringUtils.isNotEmpty(aTeam.getUserId().toString())) {
            aUserMapper.updateRoleById(aTeam.getUserId(), "0");
        }
        aTeam.setCreateTime(DateUtils.getNowDate());
        aTeam.setTeNum(1);
        aTeamMapper.insertATeam(aTeam);

        CompletableFuture.runAsync(() -> {
            try {
                //生成二维码
                WxMaQrcodeService qrcodeService = WeChatUtils.getMiniWxMaService().getQrcodeService();

                AOss oss = aossMapper.getCurrentOss();
                String url = "";
                if(oss.getCurrentType().equals("2")){
                    url =  oss.getBucket();
                }
                //默认"release" 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"
                SysConfig qrCode = sysConfigMapper.checkConfigKeyUnique("qr_code");
                byte[] imageByte = qrcodeService.createWxaCodeUnlimitBytes("teamId=" + aTeam.getId(), configureGlobalMapper.selectConfigureGlobalById(1l).getQrCodeUrl(), false, qrCode.getConfigValue() == null ? "" : qrCode.getConfigValue(), 430, true, null, false);
                String name = UUID.randomUUID() + ".jpg";
                String upload = FileUploadUtils.upload(new MultipartFileImpl(imageByte, name));
                String allUrl = url+upload.replaceAll("/profile//", "/profile/");
                aTeam.setQrCode(allUrl);
                aTeamMapper.updateATeam(aTeam);
            } catch (Exception e) { }
        });

        //生成团队详情
        ATeamInfo info = new ATeamInfo();
        info.setUserId(aTeam.getUserId());
        info.setTeamId(aTeam.getId());
        info.setReviewStatus("1");
        info.setApplicationTime(DateUtils.getNowDate());
        info.setThroughTime(DateUtils.getNowDate());
        info.setIsAgent("0");

        return aTeamInfoMapper.insertATeamInfo(info);
    }

    /**
     * 修改团队
     *
     * @param aTeamvo 团队
     * @return 结果
     */
    @Override
    public int updateATeam(ATeamVO aTeamvo) {
        final ATeamVO team = selectATeamById(aTeamvo.getId());
        Assert.notEmpty(team, "修改不能为空");
        Assert.notNull(aTeamvo.getUserId(), "用户不能为空");
        if (!team.getUserId().equals(aTeamvo.getUserId())) {
            aUserMapper.updateRoleById(team.getUserId(), "2");
            aUserMapper.updateRoleById(aTeamvo.getUserId(), "0");
            aTeamInfoMapper.updateUserIdToUserId(team.getId(), team.getUserId(), aTeamvo.getUserId());
        }
        aTeamvo.setUpdateTime(DateUtils.getNowDate());
        return aTeamMapper.updateATeam(aTeamvo);
    }

    /**
     * 解绑团队的代理商
     *
     * @param  id 团队id
     * @return 结果
     */
    public int updateATeamUserId(Long id) throws IOException, WxErrorException {
        return aTeamMapper.updateATeamUserId(id);
    }

    /**
     * 批量删除团队
     *
     * @param ids 需要删除的团队主键
     * @return 结果
     */
    @Override
    public int deleteATeamByIds(Long[] ids) {
        for (Long id : ids) {
            clearTeamUserInfo(id);
        }
        return aTeamMapper.deleteATeamByIds(ids);
    }

    private void clearTeamUserInfo(Long id) {
        ATeamInfo info = new ATeamInfo();
        info.setTeamId(id);
        List<ATeamInfo> at = aTeamInfoMapper.selectATeamInfoList(info);
        for (ATeamInfo teamInfo : at) {
            aTeamInfoMapper.deleteATeamInfoById(teamInfo.getId());
            aUserMapper.updateRoleById(teamInfo.getUserId(), "2");
        }
    }

    /**
     * 删除团队信息
     *
     * @param id 团队主键
     * @return 结果
     */
    @Override
    public int deleteATeamById(Long id) {
        clearTeamUserInfo(id);
        return aTeamMapper.deleteATeamById(id);
    }

    @Override
    public ATeam getUserATeam() {
        final ATeam team = aTeamMapper.getUserATeam(LoginUtils.getUser().getId());
        Assert.notEmpty(team, "普通用户不能获取团队信息");
        return team;
    }
}
